package co.infinum.goldfinger.example;

import co.infinum.goldfinger.Goldfinger;
import co.infinum.goldfinger.example.widget.ProgressDialog;
import ohos.aafwk.ability.Ability;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.components.Component;
import ohos.agp.components.Text;
import ohos.agp.components.TextField;
import ohos.agp.utils.TextTool;

/**
 * ex.
 *
 * @author zh
 * @since 2021-06-25
 */
public abstract class BaseLoginAbility extends Ability {
    private ProgressDialog dialog;

    protected abstract void decryptFingerprintPin(String encryptedPin);

    protected abstract void initGoldfinger();

    private TextField pinInputView;
    private Component pinLoginButton;
    private Component fingerprintLoginButton;
    private Text errorView;
    private Component resetButton;
    private MockLoginService loginService = new MockLoginService();
    private MockLoginService.Callback callback = new MockLoginService.Callback() {
        @Override
        public void onFailure() {
            errorView.setVisibility(Component.VISIBLE);
            errorView.setText("Invalid PIN");
        }

        @Override
        public void onSuccess() {
            navigateToSettings();
        }
    };


    protected void handleGoldfingerError(String errorMessage) {

        getUITaskDispatcher().asyncDispatch(new Runnable() {
            @Override
            public void run() {
                dismissDialog();
                errorView.setVisibility(Component.VISIBLE);
                errorView.setText(errorMessage);
            }
        });
    }

    protected void handleGoldfingerResult(Goldfinger.Result result) {
        getUITaskDispatcher().asyncDispatch(new Runnable() {
            @Override
            public void run() {
                dismissDialog();
                if (result.type() == Goldfinger.Type.SUCCESS) {
                    loginService.login(result.value(), callback);
                } else {
                    errorView.setVisibility(Component.VISIBLE);
                    String formattedResult = String.format("%s - %s", result.type().toString(), result.message());
                    errorView.setText(formattedResult);
                }
            }
        });
    }

    @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);
        setUIContent(ResourceTable.Layout_ability_login);
        initGoldfinger();
        initViews();
        initListeners();
    }

    @Override
    protected void onActive() {
        super.onActive();
        pinLoginButton.setEnabled(pinInputView.getText().toString().length() == 4);
        fingerprintLoginButton.setEnabled(SharedPrefs.getFingerprintPin() != null);
    }

    private void initListeners() {
        pinInputView.addTextObserver(new SimpleTextWatcher() {
            @Override
            public void onTextChanged(String text) {
                if (TextTool.isNullOrEmpty(text)) {
                    return;
                }
                String newStr = text;
                newStr = newStr.replaceAll("[^0-9]", "");
                if (text.length() > 4) {
                    newStr = text.substring(0, 4);
                }

                pinInputView.setText(newStr);
                errorView.setVisibility(Component.HIDE);
                pinLoginButton.setEnabled(newStr.length() == 4);
            }
        });

        pinLoginButton.setClickedListener(v -> {
            errorView.setVisibility(Component.HIDE);
            loginService.login(pinInputView.getText().toString(), callback);
        });

        fingerprintLoginButton.setClickedListener(v -> {
            errorView.setVisibility(Component.HIDE);
            String encryptedPin = SharedPrefs.getFingerprintPin();
            showDialog();
            decryptFingerprintPin(encryptedPin);
        });

        resetButton.setClickedListener(v -> {
            SharedPrefs.clear();
            Intent intent = new Intent();
            // 通过Intent中的OperationBuilder类构造operation对象，指定设备标识（空串表示当前设备）、应用包名、Ability名称
            Operation operation = new Intent.OperationBuilder()
                    .withDeviceId("")
                    .withBundleName("co.infinum.goldfinger.example")
                    .withAbilityName("co.infinum.goldfinger.example.ChooseImplementationAbility")
                    .build();
            // 把operation设置到intent中
            intent.setOperation(operation);
            startAbility(intent);
            terminateAbility();
        });
    }

    private void initViews() {
        pinInputView = (TextField) findComponentById(ResourceTable.Id_pinInputView);
        pinLoginButton = findComponentById(ResourceTable.Id_pinLoginButton);
        fingerprintLoginButton = findComponentById(ResourceTable.Id_fingerprintLoginButton);
        errorView = (Text) findComponentById(ResourceTable.Id_errorView);
        resetButton = findComponentById(ResourceTable.Id_resetButton);
    }

    private void navigateToSettings() {
        Class<?> cls = SharedPrefs.isRxExample() ? RxSettingsAbility.class : SettingsAbility.class;
        Intent intent = new Intent();
        // 通过Intent中的OperationBuilder类构造operation对象，指定设备标识（空串表示当前设备）、应用包名、Ability名称
        Operation operation = new Intent.OperationBuilder()
                .withDeviceId("")
                .withBundleName("co.infinum.goldfinger.example")
                .withAbilityName(cls)
                .build();
        // 把operation设置到intent中
        intent.setOperation(operation);
        startAbility(intent);

    }

    private void showDialog() {
        dialog = new ProgressDialog(this);
        dialog.show();
    }

    private void dismissDialog() {
        dialog.hide();
    }
}
